package com.leonzhangxf.vdt.formatting;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.number.NumberFormatAnnotationFormatterFactory;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;

import java.util.Date;

/**
 * A demonstrate for field formatting.
 *
 * @author leonzhangxf
 * @date 20190423
 */
@Configuration
@ComponentScan({"com.leonzhangxf.vdt.formatting"})
public class ApplicationForFormattingStarter {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
            new AnnotationConfigApplicationContext(ApplicationForFormattingStarter.class);

        ConversionService conversionService = applicationContext.getBean(ConversionService.class);
        if (conversionService.canConvert(String.class, Date.class)) {
            Date date = conversionService.convert("20190423", Date.class);
            System.out.println(date);

            System.out.println(conversionService.convert(date, String.class));
        }
    }

    @Bean
    public FormattingConversionService conversionService() {
        // Use the DefaultFormattingConversionService but do not register defaults
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);

        // Ensure @NumberFormat is still supported
        conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory());

        // Register date conversion with a specific global format
        DateFormatterRegistrar registrar = new DateFormatterRegistrar();
        registrar.setFormatter(new DateFormatter("yyyyMMdd"));
        registrar.registerFormatters(conversionService);
        return conversionService;
    }
}
